use reqwest::Client;
use tracing::{info, error};
use futures::StreamExt;

use crate::models::*;

#[derive(Clone)]
pub struct AiService {
    client: Client,
    api_key: String,
    api_url: String,
    pool: sqlx::MySqlPool,
}

impl AiService {
    pub fn new(api_key: String, pool: sqlx::MySqlPool) -> Self {
        let client = Client::new();
        let api_url = "https://api.deepseek.com/v1/chat/completions".to_string();
        Self { client, api_key, api_url, pool }
    }

    /// 流式聊天方法
    pub async fn chat_stream(
        &self, 
        request: ChatRequest,
        tx: tokio::sync::mpsc::Sender<String>,
    ) -> Result<(), Box<dyn std::error::Error>> {
        info!("发送AI流式聊天请求");

        // 创建流式请求
        let deepseek_request = DeepSeekRequest {
            model: "deepseek-chat".to_string(),
            messages: vec![
                Message {
                    role: "user".to_string(),
                    content: request.message,
                },
            ],
            temperature: 0.7,
            max_tokens: 2000,
            stream: true,
        };

        // 发送API调用
        let response = self.client
            .post(&self.api_url)
            .header("Authorization", format!("Bearer {}", self.api_key))
            .header("Content-Type", "application/json")
            .json(&deepseek_request)
            .send()
            .await?;

        if !response.status().is_success() {
            let error_text = response.text().await?;
            error!("DeepSeek API调用失败: {}", error_text);
            return Err("AI服务暂时不可用".into());
        }

        // 获取响应流
        let mut stream = response.bytes_stream();
        
        while let Some(chunk) = stream.next().await {
            match chunk {
                Ok(chunk) => {
                    let chunk_vec = chunk.to_vec();
                    let chunk_str = String::from_utf8_lossy(&chunk_vec);
                    
                    // 处理流式数据
                    for line in chunk_str.lines() {
                        if line.starts_with("data: ") {
                            let data = &line[6..]; // 移除 "data: " 前缀
                            
                            if data == "[DONE]" {
                                let _ = tx.send("data: [DONE]\n\n".to_string()).await;
                                return Ok(());
                            }
                            
                            // 直接转发DeepSeek的响应
                            let _ = tx.send(format!("data: {}\n\n", data)).await;
                        }
                    }
                }
                Err(e) => {
                    let error_data = format!("data: {{\"error\": \"{}\"}}\n\n", e);
                    let _ = tx.send(error_data).await;
                    return Err("流式响应错误".into());
                }
            }
        }

        info!("AI流式聊天完成");
        Ok(())
    }

    /// 获取用户的聊天历史
    pub async fn get_chat_history(
        &self,
        request: HistoryRequest,
    ) -> Result<ApiResponse<HistoryResponse>, Box<dyn std::error::Error>> {
        info!("获取用户 {} 的对话历史", request.username);

        // 先根据username查找用户ID
        let user = sqlx::query!(
            "SELECT id FROM users WHERE username = ?",
            request.username
        )
        .fetch_optional(&self.pool)
        .await?;

        let user_id = match user {
            Some(user) => user.id,
            None => return Ok(ApiResponse::error("用户不存在")),
        };

        // 获取对话列表和第一条消息
        let rows = sqlx::query!(
            "SELECT c.id, c.user_id, c.datetime, 
                    (SELECT m.content FROM messages m 
                     WHERE m.conversation_id = c.id 
                     ORDER BY m.id ASC 
                     LIMIT 1) as first_message
             FROM conversations c
             WHERE c.user_id = ? 
             ORDER BY c.datetime DESC",
            user_id
        )
        .fetch_all(&self.pool)
        .await?;

        let conversations: Vec<Conversation> = rows
            .into_iter()
            .map(|row| Conversation {
                id: row.id,
                user_id: row.user_id,
                datetime: chrono::DateTime::from_naive_utc_and_offset(
                    row.datetime,
                    chrono::Utc
                ),
                first_message: row.first_message,
            })
            .collect();

        let total_count = conversations.len() as i64;
        let response = HistoryResponse {
            conversations,
            total: total_count,
        };

        info!("成功获取用户 {} 的 {} 条聊天记录", request.username, total_count);
        Ok(ApiResponse::success(response, "获取聊天历史成功"))
    }

    pub async fn get_message_history(
        &self,
        request: MessageHistoryRequest,
    ) -> Result<ApiResponse<MessageHistoryResponse>, Box<dyn std::error::Error>>{
        info!("获取对话 {} 的消息列表", request.conversation_id);

        let rows = sqlx::query!(
            "SELECT id, role, content, datetime
             FROM messages
             WHERE conversation_id = ?",
             request.conversation_id
        )
        .fetch_all(&self.pool)
        .await?;

        let messages: Vec<MessageRecord> = rows
            .into_iter()
            .map(|row| MessageRecord {
                role: row.role,
                content: row.content.unwrap_or_default(),
                datetime: chrono::DateTime::from_naive_utc_and_offset(
                    row.datetime,
                    chrono::Utc
                ),
            })
            .collect();
        let response = MessageHistoryResponse{
            messages
        };

        info!("成功获取对话 {} 的消息列表！", request.conversation_id);
        Ok(ApiResponse::success(response, "获取消息列表成功"))
    }

    pub async fn create_conversation(
        &self,
        request: CreateConversationRequest,
    ) -> Result<ApiResponse<CreateConversationResponse>, Box<dyn std::error::Error>>{
        info!("用户 {} 创建新对话",  request.username);

        // 先根据username查找用户ID
        let user = sqlx::query!(
            "SELECT id FROM users WHERE username = ?",
            request.username
        )
        .fetch_optional(&self.pool)
        .await?;

        let user_id = match user {
            Some(user) => user.id,
            None => return Ok(ApiResponse::error("用户不存在")),
        };

        // 插入新对话记录
        let result = sqlx::query!(
            "INSERT INTO conversations (user_id) VALUES (?)",
            user_id
        )
        .execute(&self.pool)
        .await?;

        let conversation_id = result.last_insert_id() as i32;
        
        let response = CreateConversationResponse {
            message: format!("对话创建成功，ID: {}", conversation_id),
            conversation_id: conversation_id
        };

        info!("用户 {} 成功创建对话，ID: {}", request.username, conversation_id);
        Ok(ApiResponse::success(response, "创建对话成功"))
    }

    pub async fn delete_conversations(
        &self,
        request: DeleteHistoryRequest
    ) -> Result<ApiResponse<DeleteHistoryResponse>, Box<dyn std::error::Error>>{
        info!("用户 {} 清空对话记录", request.username);

        // 先根据username查找用户ID
        let user = sqlx::query!(
            "SELECT id FROM users WHERE username = ?",
            request.username
        )
        .fetch_optional(&self.pool)
        .await?;

        let user_id = match user {
            Some(user) => user.id,
            None => return Ok(ApiResponse::error("用户不存在")),
        };

        // 先删除该用户的所有消息记录
        let messages_deleted = sqlx::query!(
            "DELETE m FROM messages m 
             INNER JOIN conversations c ON m.conversation_id = c.id 
             WHERE c.user_id = ?",
            user_id
        )
        .execute(&self.pool)
        .await?;

        // 再删除该用户的所有对话记录
        let conversations_deleted = sqlx::query!(
            "DELETE FROM conversations WHERE user_id = ?",
            user_id
        )
        .execute(&self.pool)
        .await?;

        let response = DeleteHistoryResponse {
            message: format!("成功删除 {} 条对话记录和 {} 条消息记录", 
                           conversations_deleted.rows_affected(), 
                           messages_deleted.rows_affected()),
        };

        info!("用户 {} 成功清空对话记录", request.username);
        Ok(ApiResponse::success(response, "删除对话记录成功"))
    }

    pub async fn create_message(
        &self,
        request: CreateMessageRequest,
    ) -> Result<ApiResponse<CreateMessageResponse>, Box<dyn std::error::Error>>{
        info!("向对话 {} 创建新消息记录", request.conversation_id);

        // 插入新消息记录
        let result = sqlx::query!(
            "INSERT INTO messages (conversation_id, role, content) VALUES (?, ?, ?)",
            request.conversation_id, request.role, request.content
        )
        .execute(&self.pool)
        .await;

        match result {
            Ok(_) => {
                info!("成功向对话 {} 创建消息记录！", request.conversation_id);
            }
            Err(e) => {
                error!("向对话 {} 创建消息记录失败: {:?}", request.conversation_id, e);
                return Ok(ApiResponse::error("消息创建失败"));
            }
        }

        let response = CreateMessageResponse{
            message: format!("消息记录创建成功！"),
        };

        Ok(ApiResponse::success(response, "创建消息成功"))
    
    }
} 

